<template>
  <Page class="bg-[#f5f7fa] min-h-screen">
    <!-- 顶部蓝色渐变背景，z-0 -->
    <view class="fixed top-0 left-0 w-full z-[3] h-[250rpx] bg-gradient-to-b from-[#2196F3] to-[#6ec6ff] rounded-b-[40rpx]"></view>

    <!-- 吸顶搜索栏 z-30 -->
    <view class="sticky top-0 z-30 px-[32rpx] pt-[32rpx] pb-[0] bg-transparent">
      <SearchView @search="handleSearch" @clear="handleClear" />
      <view class="flex overflow-x-auto gap-x-[18rpx] py-[18rpx] scrollbar-hide">
        <view
          class="px-[32rpx] py-[12rpx] rounded-[24rpx] text-[26rpx] font-medium cursor-pointer transition-all duration-200 border border-transparent whitespace-nowrap"
          :class="activeFilter === 0 ? 'bg-gradient-to-r from-[#2196F3] to-[#6ec6ff] text-white font-bold shadow border-[#2196F3]' : 'bg-[#f5f7fa] text-[#2196F3]/80'"
          @click="activeFilterType(0, 0)"
        >
          全部
        </view>
        <view
          v-for="(filter, index) in filters"
          :key="index"
          class="px-[32rpx] py-[12rpx] rounded-[24rpx] text-[26rpx] font-medium cursor-pointer transition-all duration-200 border border-transparent whitespace-nowrap"
          :class="activeFilter === index + 1 ? 'bg-gradient-to-r from-[#2196F3] to-[#6ec6ff] text-white font-bold shadow border-[#2196F3]' : 'bg-[#f5f7fa] text-[#2196F3]/80'"
          @click="activeFilterType(index + 1, filter.id)"
        >
          {{ filter.name }}
        </view>
      </view>
    </view>

    <!-- 适合人群选择 -->
    <view class="px-6 mt-3 flex items-center">
      <view class="text-[24rpx] text-gray-600 mr-2">适合人群:</view>
      <view class="flex flex-wrap gap-2 flex-1 overflow-x-auto flex-nowrap">
        <!-- 人群选项 -->
        <view 
          v-for="item in suitablePersons" 
          :key="item.id"
          class="px-3 py-1 rounded-full border transition-all duration-200 cursor-pointer"
          :class="selectedGroupId === item.id ? 'bg-blue-600 border-blue-600 text-white' : 'bg-gray-100 border-gray-300 text-gray-600'"
          @click="selectGroup(item.id)"
        >
          <text class="text-[22rpx] whitespace-nowrap">{{ item.name }}</text>
        </view>
      </view>
    </view>

    <!-- 横向滚动筛选栏 z-20 -->
    <!-- <view class="sticky top-[112rpx] z-20 px-[32rpx] bg-transparent">
      <view class="flex overflow-x-auto gap-x-[18rpx] py-[18rpx] scrollbar-hide">
        <view 
          v-for="(filter, index) in filters" 
          :key="index"
          class="px-[32rpx] py-[12rpx] rounded-[24rpx] text-[26rpx] font-medium cursor-pointer transition-all duration-200 border border-transparent whitespace-nowrap"
          :class="activeFilter === index ? 'bg-gradient-to-r from-[#2196F3] to-[#6ec6ff] text-white font-bold shadow border-[#2196F3]' : 'bg-[#f5f7fa] text-[#2196F3]/80'"
          @click="activeFilter = index"
        >
          {{ filter }}
        </view>
      </view>
    </view> -->

    <!-- 内容区整体下移 -->
    <view class="pt-[20rpx] pb-[32rpx] px-[0]">
      <view class="p-[24rpx_32rpx] flex flex-col gap-y-[28rpx]">
        <view
          v-for="(bounty, index) in bounties"
          :key="index"
          @tap="handleBountyClick(bounty)"
          class="bg-white rounded-[28rpx] p-[32rpx] shadow-lg relative flex flex-col hover:shadow-xl transition-all duration-300"
        >
          <!-- 头部 -->
          <view class="flex justify-between items-center mb-[18rpx]">
            <view class="text-[32rpx] font-bold text-[#222] flex-1 truncate">{{ bounty.title }}</view>
          </view>

          <view class="my-[10rpx] p-[18rpx] bg-gradient-to-r from-[#e6f7ff] to-[#bae7ff] rounded-[12rpx] border-l-[6rpx] border-l-[#1890ff]">
            <view class="flex justify-between text-[24rpx] mb-[6rpx] line-clamp-2"> 任务描述：{{ bounty.describe_str || bounty.desc || '' }} </view>
          </view>

          <!-- 核心数据 -->
          <view class="flex items-center mb-[18rpx]">
            <view class="flex items-center">
              <IconFont font-class-name="iconfont" class-prefix="icon" name="rijie" color="#d32f2f" size="20" class="mr-[8rpx]" />

              <view class="text-[24rpx] font-bold text-[#999]"> 金额：¥{{ Number(bounty.total_amount || bounty.amount || 0).toFixed(2) }} </view>
            </view>
            <view class="text-[24rpx] text-[#666]"> </view>
            <view class="text-[24rpx] text-[#666] ml-auto">截止日期: {{ bounty.deadline }}</view>
          </view>
          <!-- 标签 -->
          <view class="flex flex-wrap gap-x-[10rpx] gap-y-[10rpx] mb-[10rpx]">
            <view v-for="(tag, tIndex) in bounty.tags" :key="tIndex" v-show="tag" class="text-[20rpx] px-[16rpx] py-[6rpx] bg-[#e3f2fd] rounded-[10rpx] text-[#2196F3] font-medium">
              {{ tag }}
            </view>
          </view>
          <!-- 底部 -->
          <view class="flex items-center mt-[10rpx]">
            <IconFont font-class-name="iconfont" class-prefix="icon" name="weizhi" size="12" color="#555" class="mr-[8rpx]" />
            <view class="text-[22rpx] text-[#999] flex-1">{{ bounty.address || '未选择区域' }}</view>
            <nut-button size="small" type="primary" @click="handleApply(bounty.title || '未知任务')"> 查看详情 </nut-button>
          </view>
        </view>
      </view>
      <!-- 加载更多按钮 -->
      <view class="flex justify-center mt-[20rpx]">
        <nut-button size="normal" type="primary" :loading="isLoading" :disabled="isLoading || noMore" @click="loadMore" class="w-[300rpx]">
          {{ noMore ? "没有更多了" : "加载更多" }}
        </nut-button>
      </view>
    </view>
  </Page>
</template>

<script setup lang="ts">
import { computed, ref } from "vue";
import Taro from "@tarojs/taro";
import SearchView from "@/components/SearchView.vue";
import { post } from "@/utils/request";
import { onChangeTab } from "@/utils/hack";
import { IconFont } from "@nutui/icons-vue-taro";

Taro.useDidShow(() => {
  onChangeTab("hall");
});

// 定义接口（保持不变）
interface taskItem {
  id?: number;
  title?: string;
  status?: string;
  publisherAvatar?: string;
  publisherName?: string;
  pay_status?: number;
  desc?: string;
  publishTime?: string;
  deadline?: string;
  amount?: string;
  total_amount?: number;
  describe_str?: string;
  address?: string;
  tags?: string[];
  hasPhase?: boolean;
}

// 分页参数
const pageNo = ref(1); // 当前页码
const pageSize = ref(10); // 每页条数
const isLoading = ref(false); // 加载中状态
const noMore = ref(false); // 是否没有更多数据

// 筛选条件和搜索文本（保持不变）
const filters = ref<{ id: number; name: string }[]>([]);
const activeFilter = ref(0);
const searchText = ref("");

// 适合人群列表
const suitablePersons = ref<any[]>([]);
// 选中的适合人群ID
const selectedGroupId = ref<number>(0); // 默认为"不限"

// 悬赏任务数据（初始为空数组）
const bounties = ref<taskItem[]>([]);

// 筛选出pay_status为1的数据
const filteredBounties = computed(() => {
  // 过滤数组，只保留pay_status等于1的项
  return bounties.value.filter((item) => item.pay_status === 1);
});

// 切换筛选条件时重置分页
const activeFilterType = (index: number, typeid: number) => {
  activeFilter.value = index;
  resetPagination(); // 重置分页
  getTaskAll(typeid); // 重新请求数据
};

// 处理搜索时重置分页
const handleSearch = (txt: string) => {
  searchText.value = txt;
  resetPagination();
  getTaskAll(0);
};

// 处理清除搜索时重置分页
const handleClear = () => {
  searchText.value = "";
  resetPagination();
  getTaskAll(0);
};

// 选择适合人群
const selectGroup = (groupId: number) => {
  selectedGroupId.value = groupId;
  resetPagination(); // 重置分页
  getTaskAll(activeFilter.value === 0 ? 0 : filters.value[activeFilter.value - 1].id); // 重新请求数据
  
  // 显示选择提示
  const groupName = groupId === 0 ? '不限' : suitablePersons.value.find(item => item.id === groupId)?.name || '未知';
  Taro.showToast({
    title: `已选择：${groupName}`,
    icon: 'none',
    duration: 1500
  });
};

// 重置分页参数
const resetPagination = () => {
  pageNo.value = 1;
  bounties.value = [];
  noMore.value = false;
};

// 加载更多
const loadMore = () => {
  if (isLoading.value || noMore.value) return;
  pageNo.value++; // 页码+1
  getTaskAll(activeFilter.value === 0 ? 0 : filters.value[activeFilter.value - 1].id);
};

// 获取任务数据（修改为支持分页加载）
const getTaskAll = async (type: number) => {
  isLoading.value = true; // 开始加载
  try {
    const params: any = {
      pageNo: pageNo.value,
      pageSize: pageSize.value,
      taskType: type,
      recommend: 0,
    };
    if (searchText.value) {
      params.title = searchText.value;
    }

    // 添加人群参数
    params.groupTypes = selectedGroupId.value || 0;

    const res = await post("/task/all", params);
    if (res.code === 0) {
      const newData = res.data.map((item: any) => ({
        ...item.columns,
        title: item.columns.title,
        id: item.columns.id,
        amount: item.columns.total_amount,
        desc: item.columns.describe_str,
        tags: item.columns.labels?.split(",") || [],
        publisherName: item.columns.memberName,
        publisherAvatar: item.columns.avatar_url,
        deadline: item.columns.deadline,
        pay_status: item.columns.pay_status,
      }));
      console.log("看看是什么", newData);

      // 第一页直接赋值，后续页追加数据
      if (pageNo.value === 1) {
        bounties.value = newData;
      } else {
        bounties.value = [...bounties.value, ...newData];
      }

      // 判断是否还有更多数据（当前页数据小于pageSize则说明没有更多）
      noMore.value = newData.length < pageSize.value;
    }
  } catch (error) {
    console.error("获取任务数据失败：", error);
    Taro.showToast({ title: "加载失败", icon: "none" });
  } finally {
    isLoading.value = false; // 结束加载
  }
};

// 初始化获取任务类型和第一页数据
const getTaskType = async () => {
  const res = await post("/dictionary/taskType", { id: 1 });
  if (res.code === 0) {
    filters.value = res.data.map((item: any) => ({
      id: item.columns.id,
      name: item.columns.name,
    }));
  }
};

// 获取适合人群列表
const getSuitablePersons = async () => {
  try {
    const res = await post("/dictionary/groupTypes");
    console.log("res==>人群",res.data)
    if (res.code === 0 && res.data) {
      // 根据接口返回的数据结构处理人群列表
      suitablePersons.value = res.data.map((item: any) => item.columns);
      suitablePersons.value.unshift({ id: 0, name: "不限" });
    }
  } catch (error) {
    console.error("获取适合人群列表失败:", error);
    // 设置默认人群列表作为备用
    suitablePersons.value = [
      { id: 0, name: "不限" },
      { id: 1, name: "学生" },
      { id: 2, name: "上班族" },
      { id: 3, name: "自由职业者" },
      { id: 4, name: "退休人员" }
    ];
  }
};

// 初始化调用
getTaskType();
getSuitablePersons();
getTaskAll(0);

// 其他方法（保持不变）
const handleApply = (taskTitle: string) => {
  Taro.showToast({
    title: `您已申请执行任务: ${taskTitle}\n等待发布者审核...`,
    icon: "none",
    duration: 2000,
  });
};

const handleBountyClick = (bounty: taskItem) => {
  console.log("头像:", bounty.publisherAvatar); // 只打印头像URL
  console.log("名字:", bounty.publisherName); // 只打印发布者名称
  Taro.navigateTo({
    url: `/pages/webs/task-details-reward-task-platform?id=${bounty.id}&deadline=${bounty.deadline}`,
  });
};
</script>
